<?php

namespace api\controller;

use common\controller\VerifyController;
use common\service\MemberService;
use common\validate\Member;
use Exception;
use malkusch\lock\mutex\PHPRedisMutex;
use support\bootstrap\Redis;
use support\ErrorCode;
use think\Request;
use think\Response;

/**
 * 成员管理
 */
class MemberController extends VerifyController
{

    private MemberService $memberService;

    public function __construct()
    {
        parent::__construct();
        $this->memberService = MemberService::getInstance();
    }

    /**
     * 成员导入
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function import(Request $request)
    {
        $dataList = $request->param()['data_list'];
        $validate = new Member();
        $validate->scene('ImportData');
        foreach ($dataList as $index => $data) {
            if (!$validate->check($data)) {
                throw_strack_exception("data_list[{$index}]." . $validate->getError(), ErrorCode::REQUEST_PARAM_ERROR);
            }
        }

        $mutex = new PHPRedisMutex([Redis::connection()->client()], "lock-member_import", 10);
        $res = $mutex->synchronized(function () use ($dataList, $request) {
            return $this->memberService->import($dataList, $request->getTenantId());
        });

        return json(success_response('OK', $res));
    }

    /**
     * 成员列表
     * @param Request $request
     * @return Response
     * @throws \think\Exception
     */
    public function list(Request $request) 
    {
        $param = $request->param()['param'];
        $filter = $param['filter'] ?? [];
        $page = get_default_page($param);
        $res = $this->memberService->list($filter, $page);
        return json(success_response('OK', $res));
    }

}
